<template>
  <view class="py-20 px-2 bg flex flex-col items-start justify-center">
    <text class="text-[#fff] text-font-bold text-[40rpx] mb-2"> 注意： </text>
    <text class="text-[#fff]"
      >支付后师傅才会收到订单，请尽快支付，若你已支付，请忽略;此外价格是我们的统一服务费，若有其它收费师傅会当面与你结算......</text
    >
  </view>
  <view
    class="w-[90%] m-auto mt-[-140rpx] py-6 rounded text-white font-semibold text-base bg-[#f5f5f5] shadow-[0_4px_10px_rgba(0,0,0,0.15)]"
  >
    <view class="w-[80%] mx-auto mb-[20rpx]">
      <text class="text-[#333] text-[40rpx] font-bold">工单详情</text>
    </view>
    <view
      class="w-[80%] mx-auto flex flex-col items-start justify-center gap-[10rpx]"
    >
      <text class="text-[#666] text-[26rpx]">
        工单ID：{{ orderInfo?.order_id || '无' }}
      </text>
      <text class="text-[#666] text-[26rpx]">
        资产名称: {{ orderInfo?.asset_name || '无' }}
      </text>
      <text class="text-[#666] text-[26rpx]">
        损坏说明：{{ orderInfo?.damage_desc || '无' }}
      </text>
      <text class="text-[#666] text-[26rpx]">
        故障代码：{{ orderInfo?.fault_code || '无' }}
      </text>
      <text class="text-[#666] text-[26rpx]">
        故障内容详情：{{ orderInfo?.fault_detail || '无' }}
      </text>
      <text class="text-[#666] text-[26rpx]">
        期望上门时间：{{
          dayjs(orderInfo?.expected_time).format('YYYY-MM-DD HH:mm:ss') || '无'
        }}
      </text>
      <text class="text-[#666] text-[26rpx]">
        联系方式：{{ orderInfo?.contact_phone }}
      </text>
      <text class="text-[#666] text-[26rpx]">
        地址：{{ orderInfo?.repair_address || '无' }}
      </text>
      <text class="text-[#666] text-[26rpx]">
        价格：{{ orderInfo?.price || 20 }}
      </text>
      <text class="text-[#666] text-[26rpx]">
        备注：{{ orderInfo?.remark || '无' }}
      </text>
      <text class="text-[#666] text-[26rpx]">
        下单时间：{{
          dayjs(orderInfo?.created_at).format('YYYY-MM-DD HH:mm:ss') || '无'
        }}
      </text>
      <view class="w-[100%] h-[100rpx] flex items-center justify-start">
        <text class="text-[#666] text-[26rpx]"> 订单码：</text>
        <image
          :src="`https://api.2dcode.biz/v1/create-qr-code?data=${orderInfo?.id}`"
          class="w-[100rpx] h-full"
          mode="aspectFill"
          @click="saveImage"
        />
        <view class="flex items-end h-[100%]">
          <text class="text-[#666] text-[20rpx]"> 点击可保存该订单二维码 </text>
        </view>
      </view>
    </view>
  </view>
  <view
    class="bottomArea position-fixed w-[100vw] bottom-[0] pb-[40rpx] pt-[10rpx] flex items-center justify-between gap-[10rpx]"
  >
    <view>
      <text class="text-[#FF0036] text-[60rpx] font-bold ml-[80rpx]">
        ￥{{ orderInfo?.price || 20 }}
      </text>
    </view>
    <view class="flex flex items-center justify-between gap-[10rpx]">
      <view
        v-for="btn in buttons"
        :key="btn.action"
        @click="handleOrder(btn)"
        class="btn w-[200rpx] h-[80rpx] rounded-2xl font-semibold text-base bg mr-[10rpx] flex items-center justify-center"
      >
        <text>{{ btn.label }}</text>
      </view>
    </view>
  </view>

  <!-- 加载遮罩 -->
  <wd-overlay :show="show" @click="show = false">
    <view class="wrapper flex items-center justify-center h-[100vh]">
      <view
        class="block bg-white p-6 rounded-xl shadow text-center"
        @click.stop=""
      >
        <text class="text-[30rpx] text-gray-700 font-semibold"
          >处理中，请稍候...</text
        >
      </view>
    </view>
  </wd-overlay>

  <wd-popup
    v-model="popShow"
    custom-style="border-radius:20rpx; height: 600rpx; width:400rpx"
    @close="popShow = false"
  >
    <wd-picker
      :columns="technicianName"
      label="选择师傅"
      v-model="masterName"
      @confirm="handleConfirm"
    />
  </wd-popup>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import {
  getUserButtons,
  getMasterButtons,
  getAdminButtons
} from '@/pages/history/utils/generateBnt'
import { getOrderDetail } from '@/api/order'
import { masterGetAll } from '@/api/master'
import dayjs from 'dayjs'

const orderInfo = ref<RepairOrder>()
const buttons = ref<Button[]>([])
const show = ref(false) // 控制加载遮罩显示
const popShow = ref(false) // 控制弹窗显示
const masterName = ref<string>('')
const masterId = ref<number>(0)

const ruleMenu = uni.getStorageSync('rule') || 'user'

// 师傅列表
const technicians = ref<Technician[]>([])
// 师傅名称
const technicianName = computed(() => {
  return technicians.value.map((item) => item.name || '无')
})

// 确认选择师傅
const handleConfirm = async ({ value }: any) => {
  masterId.value =
    technicians.value.find((item) => item.name === value)?.id || 0
  const dispatchBtn = buttons.value.find((b) => b.action === 'dispatch')
  if (dispatchBtn && orderInfo.value) {
    await dispatchBtn.onPress(
      orderInfo.value.id,
      masterId.value,
      orderInfo.value.status
    )
  }
  popShow.value = false
}

const userOrderInfo = async (id: string) => {
  const res = await getOrderDetail<{ id: number }, RepairOrder>({
    id: Number(id)
  })
  if (res.code === 200) {
    orderInfo.value = res.data
    if (ruleMenu === 'user') {
      buttons.value = getUserButtons(orderInfo.value.status)
    } else if (ruleMenu === 'master') {
      buttons.value = getMasterButtons(orderInfo.value.status)
    } else {
      buttons.value = getAdminButtons(orderInfo.value.status)
    }
  }
}

// 获取所有师傅
const getAllTechnicians = async () => {
  const res = await masterGetAll<
    { page: number; pageSize: number },
    Technician
  >({
    page: 1,
    pageSize: 1000
  })
  if (res.code === 200) {
    technicians.value = res.data.items || []
  }
}

const handleOrder = async (btn: Button) => {
  if (btn.action === 'report') {
    // 模拟支付加载中遮罩
    show.value = true
    setTimeout(async () => {
      await btn.onPress(orderInfo.value?.id || 0, orderInfo.value?.status || 0)
      show.value = false
    }, 2000)
  } else if (btn.action === 'dispatch') {
    popShow.value = true
  } else {
    btn.onPress(orderInfo.value?.contact_phone || '')
  }
}

const saveImage = async () => {
  uni.downloadFile({
    url: `https://api.2dcode.biz/v1/create-qr-code?data=${orderInfo.value?.id}`,
    success: (res) => {
      if (res.statusCode === 200) {
        uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => {
            uni.showToast({
              title: '保存成功'
            })
          },
          fail: () => {
            uni.showToast({
              title: '保存失败'
            })
          }
        })
      }
    }
  })
}

onLoad(async (option: any) => {
  await userOrderInfo(option.id)
  await getAllTechnicians()
})
</script>

<style scoped lang="scss">
.bottomArea {
  border-top: 1px solid #4caf50;
}
.btn {
  border: 1px solid #fff;
  color: #fff;
}
</style>
